package com.zlsy.thread.synchronizedlearing;

/**
 * @author zhouliang
 * @date 2020/03/03
 * @Desc synchronized访问同一个实例的两个不同的同步方法
 **/
public class SynchronizedGetTheSameInsDifferentMethod implements Runnable {

    static SynchronizedGetTheSameInsDifferentMethod instance = new SynchronizedGetTheSameInsDifferentMethod();

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")) {
            method1();
        } else {
            method2();
        }
    }

    private synchronized void method1() {
        System.out.println("我是：" + Thread.currentThread().getName() + "我开始执行了");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "我执行结束了");
    }

    private synchronized void method2() {
        System.out.println("我是：" + Thread.currentThread().getName() + "我开始执行了");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "我执行结束了");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(instance);
        Thread thread1 = new Thread(instance);
        thread.start();
        thread1.start();
        while (thread.isAlive() || thread1.isAlive()) {
        }
        System.err.println("game over！");
    }
}
